/***********************************************************
 *
 * Gaoth
 * Copyright (c) 2011- Marcus Lundgren
 * 
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from
 * the use of this software.
 * 
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it freely,
 * subject to the following restrictions:
 *
 *  1. The origin of this software must not be misrepresented; you must not
 *     claim that you wrote the original software. If you use this software
 *     in a product, an acknowledgment in the product documentation would be
 *     appreciated but is not required.
 *
 *  2. Altered source versions must be plainly marked as such,
 *     and must not be misrepresented as being the original software.
 *
 *  3. This notice may not be removed or altered from any source distribution.
 *
 ***********************************************************/

#include "model.h"

#include <iostream>

Model::Model()
{
    _entities.push_back( NPCEntity( sf::Vector2f( 10.f, 0.f ), sf::Vector2f() ) );
    _entities.push_back( NPCEntity( sf::Vector2f( -10.f, 0.f ), sf::Vector2f() ) );
}

Model::~Model()
{

}
void Model::acquire()
{
    _lock.lock();
}

void Model::release()
{
    _lock.unlock();
}

const std::vector<Client*>& Model::get_clients() const
{
    return _clients;
}

void Model::add_client( Client* client )
{
    acquire();
    _clients.push_back( client );
    release();
}

void Model::remove_client( const int id )
{
    std::vector<Client*>::iterator it;
    //for( unsigned int i = 0 ; i < _clients.size() ; ++i )
    for( it = _clients.begin() ; it != _clients.end() ; ++it )
        if( (*it)->get_id() == id )
        {
            std::cout << "Removing client with id: " << (*it)->get_id() << '\n';
            _clients.erase( it );
            delete *it;
            *it = 0;
            break;
        }
}

void Model::remove_client( const sf::TcpSocket& socket )
{
    acquire();
    std::vector<Client*>::iterator it;
    //for( unsigned int i = 0 ; i < _clients.size() ; ++i )
    for( it = _clients.begin() ; it != _clients.end() ; ++it )
        if( (*it)->get_socket() == &socket )
        {
            Client *client = *it;
            std::cout << "Removing client with id: " << (*it)->get_id() << '\n';
            _clients.erase( it );
            delete client;
            //*it = 0;
            break;
        }
    release();
}

const std::vector<NPCEntity>& Model::get_npc_entities() const
{
    return _entities;
}

void Model::update( const float time )
{
    std::vector<NPCEntity>::iterator it;
    for( it = _entities.begin() ; it != _entities.end() ; ++it )
        it->update( time );
}
